package com.lucifer.hawkeye.ai.service.impl;

import com.lucifer.hawkeye.ai.service.ExecuteSqlService;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.google.common.collect.Maps;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import javax.sql.DataSource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

/**
 * @author lucifer
 * @date 2025/4/2 11:29
 */
@Slf4j
@Service
public class ExecuteSqlServiceImpl implements ExecuteSqlService {


    private static final ConcurrentMap<String, JdbcTemplate> jdbcTemplateMap = Maps.newConcurrentMap();

    @Resource
    private DynamicRoutingDataSource dynamicRoutingDataSource;

    @Override
    public List<Map<String, Object>> executeSql(String ds, String sql) {
        try {
            return jdbcTemplateMap.computeIfAbsent(ds, this::createJdbcTemplate).queryForList(sql);
        } catch (DataAccessException e) {
            log.error("executeSql exp {}",e.getMessage());
            throw new RuntimeException(e);
        }
    }

    private JdbcTemplate createJdbcTemplate(String ds) {
        DataSource dataSource = dynamicRoutingDataSource.getDataSource(ds);
        return new JdbcTemplate(dataSource);
    }
}
